package thermologic.core;

import java.text.MessageFormat;

/**
 * Creates adapter instances independent of hardware 
 * Uses the singleton pattern
 * 
 * @author Mauricio Rivadeneira
 */
public abstract class AdapterFactory
{
    private static Adapter adapter;
    
    /**
     * Enumeration of adapters types, each element 
     * has the name and its class path
     */
    enum AdapterType {
        ONE_WIRE_ADAPTER("thermologic.onewire.OneWireAdapter");
        
        private String className;
        
        private AdapterType(String className){
            this.className = className;
        }
        
        public String getClassName()
        {
            return className;
        }
    }
    
    /**
     * create if necesary and return the 
     * adapter instance.
     * 
     * @return Adapter instance
     */
    public static Adapter getAdapter()
    {
        if(adapter == null)
        {
            String className = null;
            try
            {
                className  = AdapterType.ONE_WIRE_ADAPTER.getClassName();
                adapter = (Adapter)Class.forName(className).newInstance();
            }
            catch(ClassNotFoundException cnfe)
            {
                throw new Error(MessageFormat.format(
                        "Error loading adapter class: ", className)
                        );
            }
            catch(InstantiationException ie)
            {
                throw new Error(MessageFormat.format(
                        "Error creating instance of adapter class: ", className)
                        );
            }
            catch(IllegalAccessException iae)
            {
                throw new Error(MessageFormat.format(
                        "Error accesing instance of adapter class: ", className)
                        );
            }
        }
        
        return adapter;
    }   
    
}
